import React, { useState, useEffect } from 'react';
import { Carousel } from 'antd';
import Roll from '../../../components/Roll';
import Nav from '../../../components/Nav';
import Choiceness from '../../../components/Choiceness';
import foodicon4 from '../../../static/img/food/foodicon4.png';
import './index.css'
import { useNavigate } from 'react-router-dom';
import { message } from 'antd';
import axios from 'axios';
export default function HomePage() {
    const [homeLi, sethomeLi] = useState([])
    const [firdayData, setfirdayData] = useState([])
    const [timedowm, settimedowm] = useState({})
    useEffect(() => {
        axios.post('http://localhost:3001/home').then((res) => {
            setfirdayData(res.data[4].goods)
            sethomeLi([res.data[0], res.data[1], res.data[2], res.data[3],])
        })
    }, [])
    const navigate = useNavigate()
    function lookCommodity(num) {
        return () => {
            navigate('/tocar?' + num)
        }
    }
    function lookFirday(num) {
        return () => {
            navigate('/fridayparticulars?' + num)
        }
    }
    function moregoods(type) {
        return () => {
            navigate('/tosearch?type=' + type)
        }
    }
    //点击购物车小图标的按钮弹出加入购物车的弹窗
    const [ischoceshop, setchoceshop] = useState({ id: '', nowprice: '', img: '' })
    function addcar(id, nowprice, img) {
        if (sessionStorage.getItem("username")) {
            const carwindow = document.getElementsByClassName('C-modul')[0]
            carwindow.className = 'C-modulshow'
            setchoceshop({ id, nowprice, img })
        } else {
            message.warning('请先登录！！')
        }

    }
    // 点击弹窗的加入购物车的按钮
    const [countaddcar, setaddcar] = useState(0)
    function addtocar() {
        setaddcar(0)
        const a = countarr.kmg.filter(v => {
            return v.ischeck === true
        })
        if (countaddcar === 0) {
            message.success('请选择数量');
        } else {
            const addshop = { g_id: ischoceshop.id, u_id: '1', g_num: countaddcar, g_g: a[0].mg }
            console.log(addshop);
            const modul = document.getElementsByClassName('C-modulshow')[0]
            modul.className = 'C-modul'
            axios.post("http://localhost:3001/addShopcar", addshop).then((res) => {
                if (res.data.code === 1) {
                    window.location.reload();
                    message.success('加入购物车成功!!')

                } else {
                    message.success('加入购物车失败!!')
                }

            })
        }

    }
    //初始化规格
    //选择加入购物车规格变色
    const [countarr, setcountarr] = useState({
        kmg: [],
    })
    useEffect(() => {

        setcountarr({
            kmg: [
                { mg: 500, ischeck: false },
                { mg: 1000, ischeck: false },
                { mg: 1500, ischeck: false },
                { mg: 2000, ischeck: false }
            ]
        })
    }, [])
    //点击减号购物车-1
    function loseone() {
        if (countaddcar > 0) {
            setaddcar(countaddcar - 1)
        } else {
            setaddcar(0)
        }
    }
    //点击改变选择规格的边框和背景
    function ischocemg(i) {
        const ischoceit = JSON.parse(JSON.stringify(countarr))
        for (let index = 0; index < ischoceit.kmg.length; index++) {
            ischoceit.kmg[index].ischeck = false
        }
        ischoceit.kmg[i].ischeck = !ischoceit.kmg[i].ischeck
        setcountarr(ischoceit)
    }
    const homeLis = homeLi.map((homeLi, i) => {
        return <li key={i}>
            <div className="head">
                <img src={foodicon4} /><span className="title">{homeLi.type}</span><span className="tip">{homeLi.tip}</span><a href="" onClick={moregoods(homeLi.id)} className="more">{'更多>'}</a>
            </div>
            <ul className="homeLi-main">
                {homeLi.goods.map((homeData, i) => {
                    return <li key={i}>
                        <img src={homeData.img} alt="" />
                        <h3 onClick={lookCommodity(homeData.id)}>{homeData.title}</h3>
                        <h4>{homeData.tip}</h4>
                        <span className="new_price">￥{homeData.new_price}</span><span className="old_price">￥{homeData.old_price}</span><i className="fa fa-shopping-cart" onClick={() => addcar(homeData.id, homeData.new_price, homeData.img)}></i>
                    </li>
                })}
            </ul>
        </li>
    })
    //自定义倒计时Hook
    function lastTime(dTime, fun) {
        var nDate = new Date(dTime);
        let itime = null
        clearInterval(itime);
        itime = setInterval(function () {
            var oDate = new Date();
            var Time = Math.floor((nDate - oDate) / 1000);
            var iD = Math.floor(Time / 86400);
            var iH = Math.floor(Time % 86400 / 3600);
            var iM = Math.floor(Time % 86400 % 3600 / 60)
            var iSe = Math.floor(Time % 60);
            if (iD === 0 && iH === 0 && iM === 0 && iSe === 0) {
                clearInterval(itime);
            }
            fun({ iD, iH, iM, iSe })
        }, 1000);
    }
    var loc = window.location.href;
    useEffect(() => {
        setInterval(() => {
            if (window.location.href !== loc) {
                window.scrollTo(0, 0)
                loc = window.location.href
            }
        }, 100);
        lastTime('2021-12-17 00:00:00', settimedowm)
    }, [])

    const firdayontentStyle = {
        width: '100%',
        height: '500px',
        color: '#fff',
        lineHeight: '500px',
        textAlign: 'center',
    };
    return (
        <div>
            <Nav num={1} />
            <div className="lunbo">
                <Roll />
            </div>
            <Choiceness />
            <ul className="homeLi">
                <li>
                    <div className="head">
                        <img src={foodicon4} /><span className="title">礼拜五</span><span className="tip">Firday</span>
                        <a href="" onClick={moregoods(5)} className="more">{'更多>'}</a>
                        <div className="timedown">
                            <i className="firdayGo">距离开始</i>
                            <span>{timedowm.iD}天</span> ：
                            <span>{timedowm.iH}</span> ：
                            <span>{timedowm.iM}</span> ：
                            <span>{timedowm.iSe}</span>
                        </div>
                    </div>
                    <Carousel autoplay >
                        <div>
                            <div style={firdayontentStyle}>
                                <ul className="homeLi-main">
                                    {firdayData.map((firdayData, i) => {
                                        return <li key={i} className="firdayLi">
                                            <img src={firdayData.img} alt="" />
                                            <h3 onClick={lookFirday(firdayData.id)}>{firdayData.title}</h3>
                                            <h4>{firdayData.tip}</h4>
                                            <h4 style={{ margin: '0' }}><i>礼拜五价 : </i>
                                                <span className="new_price">￥{firdayData.new_price}</span></h4>
                                        </li>
                                    })}
                                </ul>
                            </div>
                        </div>
                        <div>
                            <div style={firdayontentStyle}>
                                <ul className="homeLi-main">
                                    {firdayData.map((firdayData, i) => {
                                        return <li key={i} className="firdayLi">
                                            <img src={firdayData.img} alt="" />
                                            <h3 onClick={lookFirday(firdayData.id)}>{firdayData.title}</h3>
                                            <h4>{firdayData.tip}</h4>
                                            <h4 style={{ margin: '0' }}><i>礼拜五价 : </i>
                                                <span className="new_price">￥{firdayData.new_price}</span></h4>
                                        </li>
                                    })}
                                </ul>
                            </div>
                        </div>
                        <div>
                            <div style={firdayontentStyle}>
                                <ul className="homeLi-main">
                                    {firdayData.map((firdayData, i) => {
                                        return <li key={i} className="firdayLi">
                                            <img src={firdayData.img} alt="" />
                                            <h3 onClick={lookFirday(firdayData.id)}>{firdayData.title}</h3>
                                            <h4>{firdayData.tip}</h4>
                                            <h4 style={{ margin: '0' }}><i>礼拜五价 : </i>
                                                <span className="new_price">￥{firdayData.new_price}</span></h4>
                                        </li>
                                    })}
                                </ul>
                            </div>
                        </div>
                    </Carousel>
                </li>
                {homeLis}
            </ul>
            <div className="C-modul">
                <h4>请选择产品规格</h4>
                <hr />
                <div className="nowprice">
                    <strong>现价：￥{ischoceshop.nowprice}</strong>&nbsp;&nbsp;&nbsp;<span>原价：{ischoceshop.oldprice}</span>
                </div>
                <div className="chocekg">
                    <div className="ischocekg">请选择规格</div>
                    {
                        countarr.kmg.map((v, i) => {
                            return (
                                <div className={v.ischeck ? 'kgnum1' : 'kgnum'} onClick={() => ischocemg(i, v.mg)} key={i}>{v.mg}</div>
                            )
                        })
                    }

                    <div className="addchar">
                        <div className="ischocekg">数量:</div>
                        <div className="addnum">
                            <div className="losenum" onClick={loseone}><i className='fa fa-minus'></i></div>
                            <div className="carnums">{countaddcar}</div>
                            <div className="losenum" onClick={() => setaddcar(countaddcar + 1)}><i className='fa fa-plus'></i></div>
                        </div>
                        <div className="to-cart" onClick={addtocar}>
                            添加到购物车
                        </div>

                    </div>

                </div>
            </div>
        </div>
    )
}
